package com.zhangjk.util;

import com.alibaba.druid.util.StringUtils;
import com.zhangjk.enums.AppConstant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;

@Component
public class UserInfoUtil {


    public JwtToken getUserInfo() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String   token = request.getHeader(AppConstant.TOKEN_NAME);
        if (!StringUtils.isEmpty(token)) {
            return getJwtInfo(token);
        }
        return null;
    }





    public static JwtToken getJwtInfo(String jwt) {
        Claims claims = Jwts.parser().setSigningKey(AppConstant.KEY).parseClaimsJws(jwt).getBody();
        JwtToken jt = new JwtToken();
        jt.setOpenid(claims.get("openid").toString());
        jt.setSession_key(claims.get("session_key").toString());
        jt.setExpiration(claims.getExpiration());
        return jt;
    }

}
